<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户注册页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 500px;
            margin: 0 auto;
            padding: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <h2>用户注册</h2>
    <form id="form1">
        <div class="form-group">
            <label for="username">用户名:</label>
            <input type="text" id="username" name="username" required>
        </div>
        <div class="form-group">
            <label for="password">密码:</label>
            <input type="password" id="password" name="password" required>
        </div>
        <button type="submit">注册</button>
    </form>
    <script>
        document.getElementById('form1').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();
        
            if (!username || !password) {
                alert('请输入用户名和密码');
                return;
            }
        
            fetch('/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json', // 确保请求头正确
                },
                body: JSON.stringify({ username, password }),
            })
            .then(response => {
                if (!response.ok) {
                    // 显示具体的 HTTP 错误状态
                    return response.json().then(err => { throw new Error(err.error) });
                }
                return response.json();
            })
            .then(data => {
                alert(data.message);
                this.reset();
            })
            .catch(error => {
                alert('注册失败: ' + error.message); // 显示具体错误信息
            });
        });
        </script>
    </script>
</body>
</html>    